from flask import jsonify
from flask_cors import CORS
from mongoengine import connect

from app.common.log_utils import logger
from app.globals import scheduler, env, swagger


class FlaskInit:
    def __init__(self, app=None):
        self.app = None
        if app:
            self.init_app(app)

    def init_app(self, app=None):
        self.app = app or self.app
        if not app:
            raise LookupError('app not exist')

        CORS(app, expose_headers='x-total-count')
        scheduler.init_app(app)
        swagger.init_app(app)
        self.init_mongo()
        self.init_module()
        self.create_user_api()
        scheduler.start()

    @staticmethod
    def init_mongo():
        connect(env.db_name, alias=env.db_name, host=env.mongo_url, connect=False)

    @staticmethod
    def init_module():
        from app.mod_trade.api import init_mod_trade
        init_mod_trade()

    def create_user_api(self):
        @self.app.route('/favicon.ico')
        def favicon():
            return ''

        @self.app.route('/')
        def index():
            return self.app.send_static_file('account.html')

        @self.app.route('/<path>')
        def get_resources(path):
            return self.app.send_static_file(path)

        @self.app.route('/api/ping')
        def ping_pong():
            return 'pong'

        @self.app.route('/api/help')
        def get_help():
            endpoints = [rule.rule for rule in self.app.url_map.iter_rules() if rule.endpoint != 'static']
            return jsonify(dict(api_endpoints=endpoints))

        @self.app.errorhandler(Exception)
        def exception_handler(err):
            logger.exception(err)
            return jsonify({'message': repr(err)}), 500
